<?php

namespace Home\Controller;


use Think\Exception;

class WechatController extends HomeController
{
	public $APPID;               //公众号APPID
	public $SECRET;               //公众号秘钥
	public $BUSINESS_ID;          //商户号
	public $BUSINESS_SECRET;      //商户秘钥
	
	
	public function _initialize()
	{
		if (method_exists(get_parent_class($this), '_initialize')) {
			parent::_initialize();
		}
		$this->APPID = C('WX_APPID');
		$this->SECRET = C('WX_SECRET');
		$this->BUSINESS_ID = C('WX_BUSINESS_ID');
		$this->BUSINESS_SECRET = C('WX_BUSINESS_SECRET');
	}
	
	
	public function index()
	{
		echo '这里是微信控制器';
	}
	
	/* 内部方法 获取CODE
     * @param $type code类型, 默认是基础信息,静默授权
     */
	protected function get_code($type = '')
	{
		$redirect_uri = urlencode(get_domain()) . '/index.php/Wechat/get_token';
		
		$scope = $type ? $type : 'snsapi_base';
		$code = 'code';
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->APPID}&redirect_uri={$redirect_uri}&response_type={$code}&scope={$scope}&state=123#wechat_redirect";
		header("Location:$url;");  //获取
	}
	
	/* 获取token
  *   @return 成功存入当前用户token,,并返回  失败返回false
  */
	public function get_token()
	{
		$code = I('code');
		if (!$code) {
			$this->get_code();
		}
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->APPID}&secret={$this->SECRET}&code={$code}&grant_type=authorization_code";
		$result = curl_get($url);  //获取
		$result = json_decode($result['result'], 1);
		if ($result['access_token']) {
//			S('wx_access_token', $result['access_token'], $result['expires_in']);  //缓存
			session('wx_openid', $result['openid']);
			return $result['access_token'];
		} else {
//			return $result['errmsg'];
			return false;
		}
	}
	
	/* 获取用户openid
	* @param $return 成功返回用户OPENID, 失败返回false
	*/
	public function get_openid()
	{
		$wx_openid = session('wx_openid');
		file_put_contents('./a.text', $wx_openid);
		if ($wx_openid) {
			return $wx_openid;
		}
		/*如果没有,就去获取*/
		$token = $this->get_token();
		if ($token) {
			return session('wx_openid');
		} else {
			return false;
		}
	}
	
	/*调用微信JSAPI支付
	 *@param $Body 商品描述
	 * @param $Money 付款金额
	 *
	 * array(9) {
		  ["appid"] => string(18) "wxdb469ef1822a0055"
		  ["mch_id"] => string(10) "1544968631"
		  ["nonce_str"] => string(16) "owuvPvvNeBy7U575"
		  ["prepay_id"] => string(36) "wx17173638935630f55bedb9081085226100"
		  ["result_code"] => string(7) "SUCCESS"
		  ["return_code"] => string(7) "SUCCESS"
		  ["return_msg"] => string(2) "OK"
		  ["sign"] => string(32) "A4D55CE56BC039FAA9B6B15543227367"
		  ["trade_type"] => string(5) "JSAPI"
		}
	 * */
	public function wx_pay($Body = '测试商品', $Money = 1)
	{
		try {
			$openid = session('wx_openid') ? session('wx_openid') : 'ojXxj1j_AQpwJWKzxaLZ2R6-BXNk';
			//1,检测参数
			if (!$openid) {
				throw new Exception('缺少openid', 1);
			}
			require_once APP_PATH . '\Common\Common\Wx_pay\lib\WxPay.Api.php';
			$input = new \WxPayUnifiedOrder();
			$input->SetBody($Body);
			$input->SetOpenid('ojXxj1j_AQpwJWKzxaLZ2R6-BXNk');
			$input->SetOut_trade_no(time());   //订单ID
			$input->SetTotal_fee($Money);
			$input->SetNotify_url(get_domain());
			$input->SetTrade_type('JSAPI');
			$input->SetProduct_id(123456789);  //商品ID
			
			$config = new \WxPayConfig(); //统一下单
			$result = \WxPayApi::unifiedOrder($config, $input);
			//2,检测结果
			if($result['result_code'] != 'SUCCESS' || $result['return_code'] != 'SUCCESS'){
				throw new Exception($result['return_msg'],2);
			}
			//3,返给前端的数据
			$arr = array();
			$this->array['msg'] = $result['return_msg'];
			$arr['appId'] = $config->GetAppId();  //应用ID
			$arr['timeStamp'] = time() . ''; //时间戳
			$arr['nonceStr'] = $input->GetNonce_str();  //随机数
			$arr['package'] = $result['prepay_id'];   //预付单ID
			$arr['signType'] = $config->GetSignType();   //加密方式
			$arr['paySign'] = $this->get_sign($arr);
			
			$this->array['data'] = $arr;
			$this->array['code'] = 1;
		} catch (\Exception $e) {
			$this->array['msg'] = $e->getMessage();
		}
		$this->ajaxReturn($this->array);
	}
	
	//获取签名
	public function get_sign($data)
	{
		//签名步骤一：按字典序排序参数
		ksort($data);
		$string = $this->ToUrlParams($data);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key={$this->BUSINESS_SECRET}"; //加上商户KEY
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
	
	/**
	 * 格式化参数格式化成url参数
	 */
	protected function ToUrlParams($data)
	{
		$buff = "";
		foreach ($data as $k => $v) {
			if ($k != "sign" && $v != "" && !is_array($v)) {
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	
	/**
	 * 支付接口
	 * 第一参数： $token
	 * 第二参数： $money ，单位：分
	 * 第三参数： $wx_name ，用户微信名称
	 * 刘雄柱
	 */
//	public function get_pay() {
//		$openid = 'ojXxj1j_AQpwJWKzxaLZ2R6-BXNk';
//		$money = 18;
//		//引入支付类
//		$result = include(APP_PATH.'/Common/Common/WxPay/Pay.class.php');
//		if(!$result) exit('支付类未引入，联系管理员');
//		$pay = new \pay();
//		//play方法里做了成功或失败的处理，成功返回code=1,带其他数据 ； 失败返回code=0,附带失败原因
//		echo $pay->pay($openid,$money);
//	}
//	/*
//	支付回调接口
//	刘雄柱
//	*/
//	//支付回调URL处理
//	public function pay_back(){
//		echo 'success'; //先告诉微信,我已经收到信息,不要再回调我浪费资源
//		$result = require(APP_PATH.'/Common/Common/WxPay/Pay.class.php');
//		if(!$result) exit('false');
//		$pay = new \pay();
//		$pay->pay_back(); //play方法里面已经做了成功或失败的处理
//	}
	
	
}